var args = arguments[0] || {};

var UsieModel = require('viewmodel/UsieModel'), InvitationModel = require("viewmodel/InvitationModel");

var ViewNavigator = require('utils/ViewNavigator');
var SockJS = require('utils/sockjs-tt');
var Stomp = require('utils/stomp');

var fb = Alloy.Globals.Facebook, me = null;

var Home = function(args) {
	$.home.addEventListener("open", init);
	Ti.App.addEventListener("new_invited", processInvitation);
	subscribe();
};

function processInvitation(e) {
	var invitedUsers = [];

	for (var i = 0, users = e.aux.listInvited; i < users.length; i++) {
		if (me.id === users[i].externalId && users[i].invitationStatus === "PENDING") {
			invitedUsers.push(users[i]);

			askForInvitation(e.aux.usieId, users[i].invitationId);
			
		}
	}
}

function askForInvitation(usieId, invitationId) {
	
	var inviteConfirmation = Ti.UI.createAlertDialog({
		title : 'Has sido invitado a la usie ' + usieId,
		message : "¿Deseas unirte?",
		buttonNames : ['Aceptar', 'Cancelar']
	});

	inviteConfirmation.show();

	var f = e;
	
	inviteConfirmation.addEventListener('click', function(e){
		var userAccepted;

		if (e.index === 0) {
			userAccepted = true;
		} else {
			userAccepted = false;
		}
		updateInvitation(usieId, invitationId, userAccepted);
		
		var data = {};
		data.me = me;
		data.id = usieId;
		(userAccepted) ? ViewNavigator.navigateToView("SelfieView", data) : undefined;

	});
	
}

function init(e) {

	fb.requestWithGraphPath('me', {
		fields : 'id,name,picture'
	}, 'GET', function(e) {
		if (e.success) {
			//alert( JSON.stringify(e) );
			var data = JSON.parse(e.result);
			me = data;
			$.name.setText(data.name);
			//$.userIcon.image = data.picture.data.url;

			$.userIcon.image = "https://graph.facebook.com/" + data.id + "/picture?type=large";

		} else if (e.error) {
			alert(e.error);
		} else {
			alert('Unknown response');
		}
	});

}

$.newSelfie.addEventListener("click", createSelfie);

function createSelfie() {
	var callbackOk = function(data) {
		data.me = me;
		// todo: pasar la usie que se creo...
		ViewNavigator.navigateToView("SelfieView", data);
	};

	var callbackError = function(error) {
		alert("Error" + error);
	};

	UsieModel.createUsie(callbackOk, callbackError);
}

function retry() {

	var url = Alloy.CFG.wsUrl;
	var socket = new SockJS(url);
	var client = Stomp.over(socket);
	client.connect({}, function() {
		client.subscribe("/topic/invitation", function(message) {
			//alert("/topic/hello: " + message);
			$.recibed.value = $.recibed.value + "/topic/invitation" + message.body + "\n";
		});
		client.subscribe("/topic/usies/2", function(message) {
			//alert("/topic/hello: " + message);
			$.recibed.value = $.recibed.value + "/topic/usies/2" + message.body + "\n";
		});
	});
}

function subscribe() {
	var WS_URL = Alloy.CFG.wsUrl,
		socket = new SockJS(WS_URL),
		client = Stomp.over(socket);
	var acceptedUsers = [];

	client.connect({}, function() {
		this.subscribe("/topic/invitation", function(message) {
			var aux = JSON.parse(message.body);
			Ti.App.fireEvent("new_invited", {
				aux : aux
			});
		});
	});

	return acceptedUsers;
}

function updateInvitation(usieId, invitationId, userAccepted) {
	successCallback = function(data) {
		ViewNavigator.navigateToView("SelfieView", data);
	};
	errorCallback = function(error) {
		alert(error);
	};
	InvitationModel.updateInvitation(usieId, invitationId, userAccepted, successCallback, errorCallback);
}

$.view = new Home(args);
